package net.gyapp.markim.module.contact;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.easyder.wrapper.base.view.WrapperSwipeActivity;
import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.gyf.barlibrary.ImmersionBar;

import net.gyapp.markim.R;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.entity.GroupEntity;
import net.gyapp.markim.core.entity.MemberEntity;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.collect.UserIntroduceActivity;
import net.gyapp.markim.module.contact.adapter.ContactsAdapter;
import net.gyapp.markim.module.contact.vo.ContactHeaderEntity;
import net.gyapp.markim.module.message.ConversationActivity;
import net.gyapp.markim.utils.SimpleTextWatcher;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/8/30
 * Version: 1.0
 * Desc:
 */


public class ContactSearchActivity extends WrapperSwipeActivity<CommonPresenter> {

    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    ContactsAdapter adapter;

    public static Intent getIntent(Context context) {
        return new Intent(context, ContactSearchActivity.class);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_contact_search;
    }

    @Override
    protected void setImmersionBar() {
        ImmersionBar.with(this)
                .statusBarView(R.id.status_view)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {

        adapter = new ContactsAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(adapter);

        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                MultiItemEntity item = adapter.getItem(position);
                if (item instanceof MemberEntity) {
                    startActivity(UserIntroduceActivity.getIntent(mActivity, (MemberEntity) item));
                } else if (item instanceof GroupEntity) {
                    startActivity(ConversationActivity.getIntent(mActivity, ImHelper.generateConversation((GroupEntity) item)));
                }
            }
        });

        etInput.setImeActionLabel("搜索", EditorInfo.IME_ACTION_SEARCH);
        etInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH && v.getId() == R.id.et_input) {
                    String s = v.getText().toString();
                    if (!TextUtils.isEmpty(s)) {
                        search(String.format("%1$s%2$s%3$s", "%", s, "%"));
                    }
                }
                return false;
            }
        });
        etInput.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    adapter.getData().clear();
                    adapter.notifyDataSetChanged();
                } else {
                    search(String.format("%1$s%2$s%3$s", "%", editable.toString(), "%"));
                }
            }
        });

        getRootView().postDelayed(new Runnable() {
            @Override
            public void run() {
                setKeyboardVisible(etInput, true);
            }
        }, 100);
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {

    }


    @Override
    protected int getTitleState() {
        return TITLE_NONE;
    }


    @Override
    protected void onDestroy() {
        setKeyboardVisible(getCurrentFocus(), false);
        super.onDestroy();
    }

    @OnClick({R.id.tv_cancel})
    void click(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                onBackPressedSupport();
                break;
        }
    }

    private void search(final String s) {
        TaskScheduler.execute(new Task<List<MultiItemEntity>>() {
            @Override
            public List<MultiItemEntity> doInBackground() throws InterruptedException {
                List<MultiItemEntity> list = new ArrayList<>();
                List<GroupEntity> groupList = ImHelper.getGroupList(s);
                if (groupList != null && groupList.size() > 0) {
                    list.add(new ContactHeaderEntity("群聊", "群聊", ContactsAdapter.TYPE_CONTACT_HEADER));
                    list.addAll(groupList);
                }
                List<MemberEntity> friendList = ImHelper.getFriendList(s);
                if (friendList != null && friendList.size() > 0) {
                    list.add(new ContactHeaderEntity("好友", "好友", ContactsAdapter.TYPE_CONTACT_HEADER));
                    list.addAll(friendList);
                }
                return list;
            }

            @Override
            public void onSuccess(List<MultiItemEntity> result) {
                adapter.setNewData(result);
            }
        });
    }
}
